#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: tangzhichao

from pathlib import Path
from typing import Optional, Union
from .slicers.selector import SliceStrategySelector
from .factory import ExtractorFactory
from .extractors.base import (
    ContentExtractor,
    UnsupportedFormatError,
    FileReadError
)


class DocumentService:
    """文档处理服务"""

    def __init__(
            self,
            slice_strategy: str = "recursive", # 默认基于句子递归切片
            chunk_size: int = 500,
            chunk_overlap: int = 50
    ):
        self.strategy = SliceStrategySelector.get_strategy(
            strategy_name=slice_strategy,
            chunk_size=chunk_size,
            chunk_overlap=chunk_overlap
        )
        self.factory = ExtractorFactory

    # 文档切片处理
    def process_document(
            self,
            raw_text: Optional[str] = None,
            query: Optional[str] = None
    ) -> dict:
        return {
            "strategy": self.strategy.strategy_name,
            "chunks": self.strategy.split(raw_text),
        }

    @property
    def supported_strategies(self) -> list:
        """获取支持的切片策略"""
        return SliceStrategySelector.list_strategies()


    def extract_content(self, file_path: Union[str, Path]) -> str:
        """
        提取文档内容
        :param file_path: 文件路径
        :return: 提取的文本内容
        :raises: UnsupportedFormatError, FileReadError
        """
        file_path = str(file_path)
        extractor = self.factory.get_extractor(file_path)
        return extractor.extract(file_path)

    def batch_extract(self, file_paths: list) -> dict:
        """
        批量提取文档内容
        :param file_paths: 文件路径列表
        :return: 字典格式结果 {文件路径: 内容或错误信息}
        """
        results = {}
        for path in file_paths:
            try:
                results[str(path)] = self.extract_content(path)
            except Exception as e:
                results[str(path)] = str(e)
        return results

    @property
    def supported_formats(self) -> list:
        """获取支持的文件格式列表"""
        return self.factory.supported_formats()

